﻿//---------------------------------------------------------------------
//  This file is part of the Microsoft .NET Framework SDK Code Samples.
// 
//  Copyright (C) Microsoft Corporation.  All rights reserved.
// 
//This source code is intended only as a supplement to Microsoft
//Development Tools and/or on-line documentation.  See these other
//materials for detailed information regarding Microsoft code samples.
// 
//THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
//KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//PARTICULAR PURPOSE.
//---------------------------------------------------------------------

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Reflection;
using System.IO;
using System.IO.Ports;
using Microsoft.VisualBasic;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using System.Net.NetworkInformation;
using System.Threading;
namespace FPGAGUI
{
    /// <summary>
    /// Summary description for form.
    /// </summary>
    public partial class Form1 : System.Windows.Forms.Form
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;
        private System.Threading.Thread DrawThread;
       //private Form regstable = new Form();
        private Form2 dis2demo = new Form2();
        Background port1=new Background("COM9");
        private byte[] sendPair = new byte[2];//address ,register's value
        //< datagridview content
       // private Panel buttonPanel = new Panel();
        //private DataGridView RegsDataGridView = new DataGridView();
       // private Button addNewRowButton = new Button();
        //private Button deleteRowButton = new Button();
        //>
        public Form1()
        {
            InitializeComponent();
            //demo.RefreshRegsbutton2.Click += new System.EventHandler(this.RefreshRegsbutton2_Click);
            dis2demo.askFatherRefresh+= new Form2.contactFatherHandler(this.dis1_RefreshRegsbutton2_Click);
            dis2demo.askFatherHideMe+=new Form2.contactFatherHandler(this.dataviewshowSwitch_Click);
            dis2demo.askFatherAutoRefresh += new Form2.contactFatherHandler(this.dis1_AutoRefreshCheckBox_CheckedChanged);
        }

       
        //打开串口的方法
         public void OpenPort()
         {
             try
              {
                  port1.Open();
              }
              catch { }
              if (port1.IsOpen)
              {
                  port1.Write("$RD;");
                  Thread.Sleep(500);
                  MessageBox.Show("the port is opened!");
                  
                  
              }
              else
              {
                  //Console.WriteLine("failure to open the port!");
                  MessageBox.Show("failure to open the port!");
              }
          }



  
          //关闭串口的方法
         public void ClosePort()
         {
             port1.Close();
             //add_log_message("串口已关闭");
             if (!port1.IsOpen)
             {
                 //Console.WriteLine("the port is already closed!");
                 timer1.Enabled = false;
                 MessageBox.Show("the port is already closed!");
             }
         }
  
          //向串口发送数据
       
       
        // Event handlers
        private void Display1_Load(object sender, System.EventArgs e)
        {
            
            ADDRtextBox1.Text = "00";
            VALtextBox2.Text = "00";
            update_serial_port_status();
            setModeFinish.Enabled = false;

        }

        private void update_serial_port_status()
        {
            if (port1.IsOpen == true)
            {
                SerialSwitchbutton3.Text = "关闭串口";
                label4.Text = "串口已打开";

                ADDRtextBox1.Enabled = true;
                VALtextBox2.Enabled = true;
                Sendbutton1.Enabled = true;
                dis2demo.AutoRefreshCheckBox.Enabled = true;
                dis2demo.RefreshRegsbutton2.Enabled = true;

            }
            else
            {
                SerialSwitchbutton3.Text = "打开串口";
                label4.Text = "串口已关闭，请打开串口";

                ADDRtextBox1.Enabled = false;
                VALtextBox2.Enabled = false;
                Sendbutton1.Enabled = false;
                dis2demo.AutoRefreshCheckBox.Enabled = false;
                dis2demo.RefreshRegsbutton2.Enabled = false;

                
            }
        }
        void Display1_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            timer1.Enabled = false;
            if (port1.IsOpen)
            {
                try
                {
                    ClosePort();
                    
                }
                catch { }
            }
        }	

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //try_to_open_serial_port();
            //update_serial_port_status();
        }
        private void try_to_open_serial_port()
        {
            string comport;
            comport = (string)this.comboBox1.Text;
            string subCOM=comport.Substring(0,3);
            int ii;
            int findflag = 0;
            for (ii = 1; ii < 9; ii++)
            {
                if (subCOM == "COM" && (comport[3] - '0'== ii))
                {
                    port1 = new Background(comport);
                    OpenPort();
                    findflag = 1;
                }
            }
            if (findflag == 0)
            {
                MessageBox.Show("请选择一个串口！\r\n");
            }
                
            //update_serial_port_status();
        }
       
       


        private void refresh_display_reg()
        {
            DrawThread = new Thread(new ThreadStart(ReadRegs));
            DrawThread.Name = "ReadRegs";
            DrawThread.Priority = System.Threading.ThreadPriority.Normal;
            DrawThread.Start(); 
        }
        private void ReadRegs()
        {
            try
            {
                //byte i;
                port1.Write("$RD;");
                Thread.Sleep(100);
                refresh_date_gird();


            }
            catch (Exception ex)
            {
                MessageBox.Show("串口错误！rty");
            }
        }

  


        private void refresh_date_gird()
        {

            for (int ii = 0; ii < 256; ii++)
            {
                dis2demo.RegVals[ii] = port1.getRegValRO(ii);
            }
            dis2demo.PopulateDataGridView();
          
        }

        private void ADDRtextBox1_TextChanged(object sender, EventArgs e)
        {
            string reg_addr;
            
            if (this.ADDRtextBox1.Text.Length == 2)
            {
                string standardm = "0";
                standardm = this.ADDRtextBox1.Text.Trim();
                Regex digitregex = new Regex("^[0-9A-F]{1,2}$");
                if (digitregex.IsMatch(standardm) == false)
                {
                    MessageBox.Show("输入错误！\r\n");
                }
                else
                {
                    reg_addr = this.ADDRtextBox1.Text.ToString();
                    byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(reg_addr);

                    sendPair[0] = (byte)(port1.ASCII2HEX(byteArray[0]) * 16 +port1.ASCII2HEX(byteArray[1]));
                    //port1.setSendPair(addrtemp, 0);
                }
            }
        }

        private void VALtextBox2_TextChanged(object sender, EventArgs e)
        {
            string reg_addr;
            
            if (this.VALtextBox2.Text.Length == 2)
            {
                string standardm = "0";
                standardm = this.ADDRtextBox1.Text.Trim();
                Regex digitregex = new Regex("^[0-9A-F]{1,2}$");
                if (digitregex.IsMatch(standardm) == false)
                {
                    MessageBox.Show("输入错误！\r\n");
                }
                else
                {
                    reg_addr = this.VALtextBox2.Text.ToString();
                    byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(reg_addr);

                    sendPair[1] = (byte)(port1.ASCII2HEX(byteArray[0]) * 16 + port1.ASCII2HEX(byteArray[1]));
                   // port1.setSendPair(valtemp, 1);
                }
            }

        }


        //private void DECradioButton1_CheckedChanged(object sender, EventArgs e)
        //{
        //    refresh_date_gird();
        //}

        //private void HEXradioButton2_CheckedChanged(object sender, EventArgs e)
        //{
        //    refresh_date_gird();
        //}

   
        private void dis1_AutoRefreshCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            if (dis2demo.AutoRefreshCheckBox.Checked == true)
            {
                if (port1.IsOpen == false)
                {
                    dis2demo.AutoRefreshCheckBox.Checked = false;
                    MessageBox.Show("请先打开串口");
                    timer1.Enabled = false;
                    dis2demo.RefreshRegsbutton2.Enabled = true;
                }
                else
                {
                    dis2demo.RefreshRegsbutton2.Enabled = false;
                    timer1.Enabled = true;
                }
            }
            else
            {
                timer1.Enabled = false;
                dis2demo.RefreshRegsbutton2.Enabled = true;
            }
        }


       

        private void HRbutton4_Click(object sender, EventArgs e)
        {
            bool timer_previous_status = timer1.Enabled;
            timer1.Enabled = false;
            Thread.Sleep(100);
            port1.Write("$HR;");
            Thread.Sleep(100);
            timer1.Enabled = timer_previous_status;
        }

        private void SRbutton5_Click(object sender, EventArgs e)
        {
            bool timer_previous_status = timer1.Enabled;
            timer1.Enabled = false;
            Thread.Sleep(100);
            port1.Write("$SR;");
            Thread.Sleep(100);
            timer1.Enabled = timer_previous_status;
        }

        private void Sendbutton1_Click(object sender, EventArgs e)
        {
            try
            {
                bool previous_timer_status = timer1.Enabled;
                timer1.Enabled = false;
                Thread.Sleep(100);
                WROneReg(this.sendPair);
                Thread.Sleep(100);
                timer1.Enabled = previous_timer_status;

            }
            catch (Exception ex)
            {
                MessageBox.Show("串口错误！");
            }
        }
        private void WROneReg(byte[] addr_val)
        {
            port1.Write("$WR");
            port1.Write(addr_val,0,2);
            port1.Write(";");
        }
        private void WR_Regs(byte[] paddr, byte[] pval, int count)
        {
            port1.Write("$WR");
            byte[] tmppairs = new byte[2*count];
            for (int ii = 0; ii < count; ii++)
            {
                tmppairs[2*ii] = paddr[ii];
                tmppairs[2*ii + 1] = pval[ii];
            }
           port1.Write(tmppairs, 0, 2 * count);
           port1.Write(";");
        }
        private void SerialSwitchbutton3_Click(object sender, EventArgs e)
        {
            if (port1.IsOpen == true)
                ClosePort();
            else
                try_to_open_serial_port();
            update_serial_port_status();
        }

        private void dataviewshowSwitch_Click(object sender, EventArgs e)
        {
            
            if (dataviewshowSwitch.Text == "showRegs")
            {
                dis2demo.Show();
                dataviewshowSwitch.Text = "hideRegs";
            }
            else if (dataviewshowSwitch.Text == "hideRegs")
            {
                dis2demo.Hide();
                dataviewshowSwitch.Text = "showRegs";
            }
        }

        public  void dis1_RefreshRegsbutton2_Click(object sender, EventArgs e)
        {
           // if(dis2demo.AutoRefreshCheckBox.Checked==false&& port1.IsOpen)
                 refresh_display_reg();
            //MessageBox.Show(('A'-65).ToString());
            //
        }
       
       

       
        private static string ToHexString(byte[] bytes)
        {
            string hexString = string.Empty;
            if(bytes!=null)
            {
                StringBuilder strB=new StringBuilder();
                for(int i=0;i<bytes.Length;i++)
                {
                    strB.Append(bytes[i]);
                }
                hexString = strB.ToString();
            }
            return hexString;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (dis2demo.AutoRefreshCheckBox.Checked && port1.IsOpen)
            {
                refresh_display_reg();
            }
        }

        private void workMode_Tick(object sender, EventArgs e)
        {
            int addr1 = 0x09;
            int addr2 = 0x0A;
            int carrierSTD = 0x02;
            int PNphaseSTD=0x01;
            int PNmodeSTD=0xC0;
            int INTmodeSTD=0x20;
            int FECrateSTD=0x18;
            int QAMmodeSTD=0x07;
            int part1 = port1.getRegValRO(addr1);
            int part2 = port1.getRegValRO(addr2);
            int carrierRST=part1 & carrierSTD;
            int PNphaseRST=part1 & PNphaseSTD;
            int PNmodeRST=part2 & PNmodeSTD;
            int INTmodeRST=part2 & INTmodeSTD;
            int FECrateRST=part2 & FECrateSTD;
            int QAMmodeRST=part2 & QAMmodeSTD;
            //PNmodeRST = 3;
            switch (carrierRST)
            {
                case 0:
                    radioButton1.Checked = true;
                    break;
                case 1:
                    radioButton2.Checked = true;
                    break;
                default:
                    {
                        radioButton1.Checked = false;
                        radioButton2.Checked = false;
                    }
                    break;
            }
            switch (PNphaseRST)
            {
                case 0:
                    radioButton3.Checked = true;
                    break;
                case 1:
                    radioButton4.Checked = true;
                    break;
                default:
                    {
                        radioButton3.Checked = false;
                        radioButton4.Checked = false;
                    }
                    break;
            }
            
            switch (PNmodeRST)
            {
                case 0: 
                    radioButton5.Checked = true; 
                    break;
                case 1:
                    radioButton6.Checked = true;
                    break;
                case 2:
                    radioButton7.Checked = true;
                    break;
                default:
                    {
                        radioButton5.Checked = false;
                        radioButton6.Checked = false;
                        radioButton7.Checked = false;
                            
                    }
                    break;
            }
            switch (INTmodeRST)
            {
                case 0:
                    radioButton8.Checked = true;
                    break;
                case 1:
                    radioButton9.Checked = true;
                    break;
                default:
                    {
                        radioButton8.Checked = false;
                        radioButton9.Checked = false;
                    }
                    break;
            }
            switch (FECrateRST)
            {
                case 0:
                    radioButton10.Checked = true;
                    break;
                case 1:
                    radioButton11.Checked = true;
                    break;
                case 2:
                    radioButton12.Checked = true;
                    break;
                default:
                    {
                        radioButton10.Checked = false;
                        radioButton11.Checked = false;
                        radioButton12.Checked = false;

                    }
                    break;
            }
            switch (QAMmodeRST)
            {
                case 0:
                    radioButton13.Checked = true;
                    break;
                case 1:
                    radioButton14.Checked = true;
                    break;
                case 2:
                    radioButton15.Checked = true;
                    break;
                case 3:
                    radioButton16.Checked = true;
                    break;
                default:
                    {
                        radioButton13.Checked = false;
                        radioButton14.Checked = false;
                        radioButton15.Checked = false;
                        radioButton16.Checked = false;
                    }
                    break;
            }

        }

        private void workModeSwitch_Click(object sender, EventArgs e)
        {
            if (workModeSwitch.Text == "ShowWorkMode")
            {
                workModeTimer.Enabled = true;
                setModeFinish.Enabled = false;
                workModeSwitch.Text = "SetWorkMode";
            }
            else if (workModeSwitch.Text == "SetWorkMode")
            {
                workModeTimer.Enabled = false;
                setModeFinish.Enabled = true;
                workModeSwitch.Text = "ShowWorkMode";
            }
        }

        private void setModeFinish_Click(object sender, EventArgs e)
        {
            setModeFinish.Enabled = false;
            byte carrierSeg=0;
            byte PNphaseSeg=0;

            byte PNmodeSeg=0;
            byte INTmodeSeg=0;
            byte FECrateSeg=0;
            byte QAMmodeSeg=0;
            byte addr1 = 0x09;
            byte addr2 = 0x0A;
            int part1=0;
            int part2=0;
            if (radioButton1.Checked)
                carrierSeg = 0x00;
            if (radioButton2.Checked)
                carrierSeg = 0x02;
            if (radioButton3.Checked)
                PNphaseSeg = 0x00;
            if (radioButton4.Checked)
                PNphaseSeg = 0x01;
            if (radioButton5.Checked)
                PNmodeSeg = 0x00;
            if (radioButton6.Checked)
                PNmodeSeg = 0x40;
            if(radioButton7.Checked)
                PNmodeSeg=0x80;
            if(radioButton8.Checked)
                INTmodeSeg=0x00;
            if(radioButton9.Checked)
                INTmodeSeg=0x20;
            if(radioButton10.Checked)
                FECrateSeg=0x00;
            if(radioButton11.Checked)
                FECrateSeg=0x08;
            if(radioButton12.Checked)
                FECrateSeg=0x10;
            if(radioButton13.Checked)
                QAMmodeSeg=0x01;
            if(radioButton14.Checked)
                QAMmodeSeg=0x02;
            if(radioButton15.Checked)
                QAMmodeSeg=0x03;
            if(radioButton16.Checked)
                QAMmodeSeg=0x04;
            part1=0x80+carrierSeg+PNphaseSeg;
            part2 = PNmodeSeg + INTmodeSeg + FECrateSeg + QAMmodeSeg;
            byte [] paddr = new byte[2];
            byte[] pval = new byte[2];
            paddr[0] = addr1;
            paddr[1] = addr2;
            pval[0]=Convert.ToByte(part1);
            pval[1] = Convert.ToByte(part2);
            this.WR_Regs(paddr, pval, 2);
            //workModeTimer.Enabled = true;
            
        }

        
    }
}

